package org.example.ipersistent.mapper;

import org.dom4j.DocumentException;
import org.example.ipersistent.pojo.User;
import org.example.ipersistent.sqlSession.SqlSession;
import org.example.ipersistent.sqlSession.SqlSessionFactory;
import org.example.ipersistent.sqlSession.SqlSessionFactoryBuilder;
import org.example.ipersistent.utils.Resources;

import java.io.InputStream;
import java.util.List;

public class UserMapperImpl implements IUserMapper {

  private IUserMapper userMapper;

  public UserMapperImpl(){
    // 根据配置文件路径，加载成字节输入流存储到内存中，文件还未进行解析
    InputStream stream = Resources.getResourceAsStream("ipersistent-config.xml");
    SqlSessionFactory sqlSessionFactory = null;
    try {
      sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
    } catch (DocumentException e) {
      throw new RuntimeException(e);
    }
    SqlSession sqlSession = sqlSessionFactory.openSession(IUserMapper.class.getName());
    this.userMapper = (IUserMapper) sqlSession.getMapper(IUserMapper.class);
  }
  @Override
  public List<User> findAll() {
    List<User> users = userMapper.findAll();
    return users;
  }

  @Override
  public User findByCondition(User user) {
    User user1 = (User) userMapper.findByCondition(user);
    return user1;
  }
}
